<template>
  <view class="exception-order-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="异常工单" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 工单状态筛选 -->
            <view class="filter-item">
              <text class="filter-label">工单状态：</text>
              <up-tabs :list="statusList" :scrollable="false" @change="handleStatusChange"
                :current="currentStatus"></up-tabs>
            </view>

            <!-- 时间筛选 -->
            <view class="filter-item">
              <text class="filter-label">时间筛选：</text>
              <up-tabs :list="timeRangeList" :scrollable="true" @change="handleTimeRangeChange"
                :current="currentTimeRange"></up-tabs>
            </view>

            <!-- 自定义时间选择 -->
            <view v-if="currentTimeRange === 5" class="custom-time-section">
              <view class="time-picker-row">
                <view class="time-picker">
                  <text class="title">自定义时间</text>
                  <uni-datetime-picker type="daterange" :border="false" v-model="customTimeRange.dateRange"
                    @change="handleDateRangeChange"></uni-datetime-picker>
                </view>
              </view>
            </view>

            <!-- 泊位号搜索 -->
            <view class="filter-item">
              <up-search v-model="searchForm.berthNumber" :clearabled="true" :showAction="true" placeholder="请输入泊位号"
                @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>

            <!-- 异常类型筛选 -->
            <view class="filter-item">
              <text class="filter-label">异常类型：</text>
              <up-tabs :list="exceptionTypeList" :scrollable="true" @change="handleExceptionTypeChange"
                :current="currentExceptionType"></up-tabs>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 列表内容 -->
      <view class="exception-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              工单编号：<text class="number">{{ item.orderNo }}</text>
            </view>
            <view class="status-badge" :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">负责人：</text>
                <text class="value">{{ item.assigneeName || '未指派' }}</text>
              </view>
              <view class="item">
                <text class="label">异常类型：</text>
                <text class="value exception-type" :class="getExceptionTypeClass(item.exceptionType)">{{
                  item.exceptionType
                  }}</text>
              </view>
              <view class="item">
                <text class="label">泊位号：</text>
                <text class="value">{{ item.berthNumber }}</text>
              </view>
              <view class="item">
                <text class="label">设备编号SN：</text>
                <text class="value">{{ item.deviceSN }}</text>
              </view>
              <view class="item">
                <text class="label">停车场：</text>
                <text class="value">{{ item.parkingLot }}</text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="info" text="查看详情" class="custom-style" @click="handleViewDetail(item)"></up-button>
                <up-button v-if="currentStatus === 2" type="primary" text="处理" class="custom-style"
                  @click="handleProcess(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 处理工单弹窗 -->
    <up-popup :show="showProcessModal" mode="center" :round="10">
      <view class="process-modal">
        <view class="modal-header">
          <text class="modal-title">处理工单</text>
          <up-icon name="close" @click="closeProcessModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">处理状态：</text>
            <up-radio-group v-model="processForm.status">
              <up-radio label="已处理" name="completed"></up-radio>
              <up-radio label="无法处理" name="failed"></up-radio>
            </up-radio-group>
          </view>
          <view class="form-item">
            <text class="form-label">上传图片：</text>
            <up-upload :fileList="processForm.images" @afterRead="afterUpload" @delete="deleteImage"></up-upload>
          </view>
          <view class="form-item">
            <text class="form-label">备注：</text>
            <up-textarea v-model="processForm.remark" placeholder="请输入处理备注" maxlength="200"></up-textarea>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="info" @click="closeProcessModal">取消</up-button>
          <up-button type="primary" @click="confirmProcess">确认处理</up-button>
        </view>
      </view>
    </up-popup>

    <!-- 查看详情弹窗 -->
    <up-popup v-model:show="showDetailModal" mode="center" :round="10">
      <view class="detail-modal">
        <view class="modal-header">
          <text class="modal-title">工单详情</text>
          <up-icon name="close" @click="closeDetailModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="detail-item">
            <text class="detail-label">工单编号：</text>
            <text class="detail-value">{{ currentDetail.orderNo }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">泊位编号：</text>
            <text class="detail-value">{{ currentDetail.berthNumber }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">设备编号：</text>
            <text class="detail-value">{{ currentDetail.deviceSN }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">异常类型：</text>
            <text class="detail-value">{{ currentDetail.exceptionType }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">停车场：</text>
            <text class="detail-value">{{ currentDetail.parkingLot }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">负责人：</text>
            <text class="detail-value">{{ currentDetail.assigneeName || '未指派' }}</text>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="primary" @click="closeDetailModal">关闭</up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import { getExceptionJobList, dealExceptionJob } from '@/api';

// 工单状态选项
const statusList = [
  { name: '全部' },
  { name: '待指派' },
  { name: '待处理' },
  { name: '已处理' },
];
const currentStatus = ref(0);

// 时间筛选选项
const timeRangeList = [
  { name: '近7天' },
  { name: '近1个月' },
  { name: '近3个月' },
  { name: '近半年' },
  { name: '近1年' },
  { name: '自定义' },
];
const currentTimeRange = ref(0);

// 异常类型选项
const exceptionTypeList = [
  { name: '全部' },
  { name: '后车驶入导致结束前车订单' },
  { name: '车位长时间无订单' },
  { name: '用户修改车牌' },
  { name: '登记车牌重复' },
  { name: '人工结束订单' },
  { name: '同车位多停车中' },
  { name: '有车牌无图片' },
];
const currentExceptionType = ref(0);

// 自定义时间范围
const customTimeRange = reactive({
  startTime: '',
  endTime: '',
  dateRange: []
});

// 搜索表单数据
const searchForm = reactive({
  berthNumber: '',
});

// z-paging 组件引用
const paging = ref(null);

// 当前显示的列表数据
const currentList = ref([]);

// 处理工单相关
const showProcessModal = ref(false);
const processForm = reactive({
  status: 'completed',
  images: [],
  remark: ''
});

// 查看详情相关
const showDetailModal = ref(false);
const currentDetail = ref({});

// 工单状态切换事件
const handleStatusChange = (e) => {
  currentStatus.value = e.index;
  if (paging.value) {
    paging.value.reload();
  }
};

// 时间筛选切换事件
const handleTimeRangeChange = (e) => {
  currentTimeRange.value = e.index;
  // 如果不是自定义时间范围，则清空自定义时间
  if (currentTimeRange.value !== 5) {
    customTimeRange.dateRange = [];
    customTimeRange.startTime = '';
    customTimeRange.endTime = '';
  }
  if (paging.value) {
    paging.value.reload();
  }
};

// 异常类型切换事件
const handleExceptionTypeChange = (e) => {
  currentExceptionType.value = e.index;
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理日期范围变化
const handleDateRangeChange = (e) => {
  if (Array.isArray(e) && e.length === 2) {
    customTimeRange.startTime = e[0];
    customTimeRange.endTime = e[1];
    if (paging.value) {
      paging.value.reload();
    }
  }
};

// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  searchForm.berthNumber = '';
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.navigateTo({
    url: '/pages/work-order/index'
  });
};

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    'pending': 'status-pending',
    'completed': 'status-completed'
  };
  return statusMap[status] || '';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'completed': '已处理'
  };
  return statusMap[status] || status;
};

// 获取异常类型样式类
const getExceptionTypeClass = (type) => {
  const typeMap = {
    '后车驶入导致结束前车订单': 'type-car-conflict',
    '车位长时间无订单': 'type-no-order',
    '用户修改车牌': 'type-plate-modified',
    '登记车牌重复': 'type-plate-duplicate',
    '人工结束订单': 'type-manual-end',
    '同车位多停车中': 'type-multiple-parking',
    '有车牌无图片': 'type-no-image'
  };
  return typeMap[type] || '';
};

// 处理工单
const handleProcess = (item) => {
  processForm.status = 'completed';
  processForm.images = [];
  processForm.remark = '';
  currentDetail.value = item;
  showProcessModal.value = true;
};

// 上传图片后的回调
const afterUpload = (event) => {
  processForm.images.push({
    url: event.file.url,
    status: 'done',
    message: '上传成功',
    name: event.file.name
  });
};

// 删除图片
const deleteImage = (event) => {
  processForm.images.splice(event.index, 1);
};

// 确认处理
const confirmProcess = async () => {
  if (!processForm.remark) {
    uni.showToast({
      title: '请输入处理备注',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 准备图片URL字符串
    const fileUrls = processForm.images.map(img => img.url).join(',');
    
    // 调用API处理工单
    const res = await dealExceptionJob({
      bizCode: currentDetail.value.orderNo,
      dealRemark: processForm.remark,
      fileUrl: fileUrls || undefined,
      dealStatus: processForm.status === 'completed' ? 0 : 1 // 转换状态：completed->0, failed->1
    });
    
    if (res && res.success) {
      uni.showToast({
        title: '处理成功',
        icon: 'success'
      });
      
      closeProcessModal();
      if (paging.value) {
        paging.value.reload();
      }
    } else {
      uni.showToast({
        title: res?.msg || '处理失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('处理工单失败', error);
    uni.showToast({
      title: '处理失败，请稍后重试',
      icon: 'none'
    });
  }
};

// 关闭处理弹窗
const closeProcessModal = () => {
  showProcessModal.value = false;
};

// 查看详情
const handleViewDetail = (item) => {
  currentDetail.value = item;
  showDetailModal.value = true;
};

// 关闭详情弹窗
const closeDetailModal = () => {
  showDetailModal.value = false;
};

// 获取异常工单列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 构建API请求参数
    const params = {
      pageNum: pageNo,
      pageSize: pageSize,
      status: currentStatus.value === 0 ? -1 : currentStatus.value - 1, // 转换状态：0全部->-1, 1待处理->0, 2已处理->1
      keyword: searchForm.berthNumber || undefined, // 泊位关键字
      errorType: currentExceptionType.value === 0 ? -1 : currentExceptionType.value - 1, // 转换异常类型
      dateType: currentTimeRange.value === 5 ? undefined : currentTimeRange.value // 日期类型
    };

    // 如果是自定义时间，添加时间参数
    if (currentTimeRange.value === 5 && customTimeRange.dateRange && customTimeRange.dateRange.length === 2) {
      params.startDate = customTimeRange.dateRange[0];
      params.endDate = customTimeRange.dateRange[1];
    }

    // 调用API获取数据
    const res = await getExceptionJobList(params);

    if (res && res.success && res.data) {
      // 转换API返回的数据格式为页面所需格式
      const records = (res.data.records || []).map(item => {
        // 状态转换：0待指派->pending, 1待处理->pending, 2已处理->completed
        const status = item.zpType === '0' || item.errorType === '1' ? 'pending' : 'completed';

        // 异常类型名称映射
        const exceptionTypeMap = {
          '0': '异常入场',
          '1': '车位长时间无订单',
          '2': '用户修改车牌',
          '3': '登记车牌重复',
          '4': '人工结束订单',
          '5': '同车位多停车中',
          '6': '有车牌无图片'
        };

        return {
          orderNo: item.bizCode || '',
          berthNumber: item.berthNo || '',
          deviceSN: item.deviceSn || '',
          exceptionType: item.errorTypeName || exceptionTypeMap[item.errorType] || '未知异常',
          status: status,
          assigneeName: item.inspectorName || '',
          createTime: item.createTime || '',
          parkingLot: item.veName || ''
        };
      });

      // 更新分页组件
      paging.value.complete(records);
    } else {
      // 处理API错误
      uni.showToast({
        title: res?.msg || '获取数据失败',
        icon: 'none'
      });
      paging.value.complete(false);
    }
  } catch (error) {
    console.error('获取异常工单列表失败', error);
    uni.showToast({
      title: '获取数据失败，请稍后重试',
      icon: 'none'
    });
    paging.value.complete(false);
  }
};

// 生成模拟数据
const generateMockData = (params) => {
  const exceptionTypes = [
    '后车驶入导致结束前车订单',
    '车位长时间无订单',
    '用户修改车牌',
    '登记车牌重复',
    '人工结束订单',
    '同车位多停车中',
    '有车牌无图片'
  ];
  const statuses = ['pending', 'completed'];
  const assigneeTypes = ['巡检员', '客服人员'];

  const records = [];
  for (let i = 1; i <= 10; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const assigneeType = assigneeTypes[Math.floor(Math.random() * assigneeTypes.length)];
    const exceptionType = exceptionTypes[Math.floor(Math.random() * exceptionTypes.length)];

    // 如果有异常类型筛选，则只返回对应类型的数据
    if (params.exceptionType > 0 && exceptionTypes[params.exceptionType - 1] !== exceptionType) {
      continue;
    }

    // 如果有状态筛选，则只返回对应状态的数据
    if (params.status > 0 && statuses[params.status - 1] !== status) {
      continue;
    }

    records.push({
      orderNo: `EO${Date.now()}${i.toString().padStart(3, '0')}`,
      berthNumber: `A${(i + 100).toString()}`,
      deviceSN: `SN${Date.now()}${i.toString().padStart(4, '0')}`,
      exceptionType: exceptionType,
      status: status,
      assigneeName: `${assigneeType}${i}`,
      createTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleString(),
      parkingLot: '停车场A区'
    });
  }

  return { records };
};

// 页面挂载时获取数据
onMounted(() => {
  if (paging.value) {
    paging.value.reload();
  }
});
</script>

<style scoped lang="scss">
.exception-list {
  padding: 20px;
}

.filter-section {
  .filter-item {
    margin-bottom: 20rpx;

    .filter-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
      display: block;
    }
  }

  .custom-time-section {
    margin-top: 20rpx;

    .time-picker-row {
      display: flex;
      align-items: center;

      .time-picker {
        width: 100%;
        display: flex;
        align-items: center;
        background-color: #f8f8f8;
        padding: 10rpx 20rpx;
        border-radius: 8rpx;
        margin-bottom: 20rpx;

        .title {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-right: 20rpx;
        }
      }

      .time-separator {
        font-size: 28rpx;
        color: #666;
        margin: 0 10rpx;
      }
    }
  }
}

// 列表卡片样式
.list-item-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .card-header {
    padding: 24rpx 30rpx 16rpx;
    border-bottom: 1px solid #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;

      .number {
        color: #1890ff;
      }
    }

    .status-badge {
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      font-size: 22rpx;

      &.status-pending {
        background: #fff2e8;
        color: #fa8c16;
      }

      &.status-completed {
        background: #f6ffed;
        color: #52c41a;
      }
    }
  }

  .card-content-box {
    padding: 20rpx 30rpx;

    .content {
      .item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          font-size: 26rpx;
          color: #666;
          flex-shrink: 0;
        }

        .value {
          font-size: 26rpx;
          color: #333;
          text-align: right;

          &.exception-type {
            font-weight: bold;

            &.type-car-conflict {
              color: #ff4d4f;
            }

            &.type-no-order {
              color: #fa8c16;
            }

            &.type-plate-modified {
              color: #722ed1;
            }

            &.type-plate-duplicate {
              color: #1890ff;
            }

            &.type-manual-end {
              color: #13c2c2;
            }

            &.type-multiple-parking {
              color: #eb2f96;
            }

            &.type-no-image {
              color: #faad14;
            }
          }
        }
      }
    }

    .card-footer {
      margin-top: 24rpx;
      padding-top: 20rpx;
      border-top: 1px solid #f5f5f5;

      .operate {
        display: flex;
        justify-content: flex-end;
        gap: 20rpx;

        .custom-style {
          border-radius: 8rpx;
          font-size: 24rpx;
        }
      }
    }
  }
}

// 弹窗样式
.process-modal,
.detail-modal {
  width: 600rpx;
  background: #fff;
  border-radius: 20rpx;

  .modal-header {
    padding: 30rpx;
    border-bottom: 1px solid #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .modal-content {
    padding: 30rpx;
    max-height: 600rpx;
    overflow-y: auto;

    .form-item,
    .detail-item {
      margin-bottom: 30rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .form-label,
      .detail-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
        display: block;
      }

      .detail-value {
        font-size: 28rpx;
        color: #666;
      }
    }
  }

  .modal-footer {
    padding: 30rpx;
    border-top: 1px solid #f5f5f5;
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
  }
}
</style>